package com.wenhao.newcode.shopee;

import com.wenhao.leetcode.structure.ListNode;

/**
 * @author Wenhao Tong
 * @create 2021-07-17 14:39
 */
public class Main6 {
    public static void main(String[] args) {
        Main6 main6 = new Main6();
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        ListNode listNode6 = new ListNode(6);
        ListNode listNode7 = new ListNode(7);

        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        listNode5.next = listNode6;
        listNode6.next = listNode7;


        ListNode listNode = main6.reverseLinkedList(listNode1,4);

        ListNode temp = listNode;
        while (temp != null) {
            System.out.println(temp.val);
            temp = temp.next;
        }
    }
    /**
     * reverse the given linked list
     * @param head ListNode类 the head of the linked list
     * @param n int整型 the N
     * @return ListNode类
     */
    public ListNode reverseLinkedList (ListNode head, int n) {
        // write code here
        ListNode newHead = new ListNode();
        ListNode pre = newHead;
        ListNode tail,next;
        while (head != null) {
            int count = 1;
            tail = head;
            while (tail.next != null && count < n) {
                tail = tail.next;
                count++;
            }
            next = tail.next;
            tail.next = null;
            reverseAll(head);
            pre.next = tail;
            pre = head;
            head.next = next;
            head = next;
        }
        return newHead.next;
    }

    public ListNode reverseAll (ListNode head) {
        if (head.next == null) {
            return head;
        }
        ListNode temp = reverseAll(head.next);
        head.next.next = head;
        head.next = null;
        return temp;
    }
}
